package com.backstage.controller;

import com.backstage.common.annotation.log.Operate;
import com.backstage.common.base.bean.Message;
import com.backstage.common.page.Page;
import com.backstage.common.uitil.TxYunUtil;
import com.backstage.entity.File;
import com.backstage.service.FileService;
import com.qcloud.cos.common_utils.CommonFileUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @TODO 文件管理
 * @Author:阮雪峰
 * @Date：2017/8/6 20:50
 * @pagekage: com.backstage.controller
 * @project: authority
 */
@Controller
@RequestMapping("/file")
public class FileController extends BaseController {

    @Resource(name = "fileService")
    private FileService fileService;

    /**
     * 文件列表
     * @param page
     * @param file
     * @return
     */
    @RequiresPermissions("sys:file:list")
    @RequestMapping("/queryByPage")
    @ResponseBody
    public Page<File> queryByPage(Page<File> page, File file){
        fileService.queryByPage(page, file);
        return page;
    }

    @Operate("文件管理：新增")
    @RequiresPermissions("sys:file:add")
    @RequestMapping("/add")
    @ResponseBody
    public Message add(HttpServletRequest request) throws Exception {
        MultipartRequest req = (MultipartRequest)request;
        List<MultipartFile> files = req.getFiles("file");
        List<File> fileList = new ArrayList<>();

        String memo = request.getAttribute("memo")==null || "".equals(request.getAttribute("memo"))?"":request.getAttribute("memo").toString();
        for (MultipartFile file : files) {
            String url = TxYunUtil.uploadFile(file.getOriginalFilename(), "img",
                    CommonFileUtils.getFileContentByte(file.getInputStream(), 0, (int) file.getSize()));

            if("".equals(url)){
                throw new RuntimeException("文件上传失败："+file.getName());
            }else {
                File file1 = new File();
                file1.setUrl(url);
                file1.setCreator(this.getLoginUser().getUid());
                file1.setMemo(memo);
                fileList.add(file1);
            }
        }
        fileService.add(fileList);
        return Message.ADD_SUCCESS;
    }

    /**
     * 删除
     * @param files
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public Message delete(@RequestBody ArrayList<File> files){
        fileService.delete(files);
        return Message.DELETE_SUCCESS;
    }
}
